<template>
  <el-form
    ref="formRef"
    :model="form"
    label-width="120px"
    :rules="rules">
    <el-form-item label="接口类型" prop="api_rest">
      <el-radio-group v-model="form.api_rest">
        <el-radio label="mapi">低码接口</el-radio>
        <el-radio label="system">系统接口</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="接口描述" prop="api_name">
      <el-input v-model="form.api_name" placeholder="名称，如：查询用户数据"></el-input>
    </el-form-item>
    <el-form-item v-if="form.api_rest !== 'system'" :label="'应用/分组路径'" prop="api_funame">
      <el-input v-model="form.api_funame" :placeholder="'所属应用/分组，如：zp/apis'"></el-input>
    </el-form-item>
    <el-form-item :label="form.api_rest === 'system' ? '接口路径' : '接口编码'" prop="api_code">
      <el-input v-model="form.api_code" :placeholder="form.api_rest === 'system' ? '接口路径，如：/admin/menutree' : '函数名称'"></el-input>
    </el-form-item>

    <el-form-item
      label=""
      label-width="0px"
      class="form-item-center">
      <el-button
        type="primary"
        @click="handleSubmitCreateApi"
      > 提交 </el-button>
      <el-button
        @click="handleCancel"
      > 取消 </el-button>
    </el-form-item>
  </el-form>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue';
import _ from 'lodash';

const props = defineProps({
  actionType: String,
  currentData: Object,
  module: Object,
  apiType: String
});

const emit = defineEmits(['close']);

const DEFAULT_FORM = {
  isPlat: true,
  api_store: 1,
  api_uuid: '',
  api_code: '',   // create/update/remove/removeBat/query/get/getSingle/getByIds',
  api_name: '',
  api_funame: '', // create/update/remove/removeBat/query/get/getSingle/getByIds',
  api_rest: 'mapi',   // '接口路径?',
  api_inparam_schema: {},     // json
  api_outparam_schema: {},    // json DEFAULT NULL,
  service_id: null,
  module_id: null
};

const validateApiCode = (rule, value, callback) => {
  let pattern = new RegExp(/^[A-Za-z0-9-_]+$/);
  let msg = '编码只能由[ 字母数字-_ ]组成';
  if (form.value.api_rest === 'system') {
    pattern = new RegExp(/^[A-Za-z0-9-_\/]+$/);
    msg = '编码只能由[ 字母数字-_/ ]组成';
  }
  if (!pattern.test(value)) {
    callback(new Error(msg));
  } else {
    callback();
  }
};

const loading = ref(false);
const form = ref(_.cloneDeep(DEFAULT_FORM));
const rules = {
  api_code: [
    { required: true, message: '请输入接口编码', trigger: 'blur' },
    {
      validator: validateApiCode,
      trigger: 'blur'
    }
  ],
  api_name: [
    { required: true, message: '请输入接口名称', trigger: 'blur' }
  ],
  api_funame: [
    { required: true, message: '请输入所属应用', trigger: 'blur' }
  ]
};

const init = () => {
  let formValue = null;
  let data = _.cloneDeep(props.currentData);

  if (data && data.api_id) {
    formValue = data;
  } else {
    formValue = _.defaults(data || {}, {
      api_rest: props.apiType || 'mapi',
      api_code: "",
      api_uuid: $utils.getNanoid()
    }, DEFAULT_FORM);
  }

  form.value = formValue || {};
};

const handleSubmitCreateApi = async () => {
  let data = _.cloneDeep(form.value);
  let id = _.get(data, 'api_id');
  let ret = null;

  if (!data.api_uuid) {
    data.api_uuid = $utils.getNanoid();
  }
  if (data.api_rest === 'system') {
    data.api_funame = '';
  }

  data.isPlat = true;
  if (id) {
    ret = await api.services.apiUpdate(id, data);
  } else {
    ret = await api.services.apiCreate(data);
  }

  if (!ret) return;

  let tid = _.get(form.value, 'tid') || `A_${_.get(ret, 'api_id')}`;

  loading.value = false;

  if (ret) {
    $jui.toast('操作成功！');
    handleCancel(tid);
  }
};

const handleCancel = (flag) => {
  emit('close', flag);
};

onMounted(() => {
  init();
});

watch(() => props.currentData, () => {
  init();
}, { deep: true });

watch(() => props.actionType, () => {
  init();
});
</script>
